import {
	baseURL
} from './common.js' //接口域名引入
import store from './store.js' //接口域名引入
function request(url, data = {}, method = 'GET', loading = false) {
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: '数据加载中...',
				mask: true
			})
		}
		// 请求前：处理data
		let token = uni.getStorageSync('token') || '';
		let locale = uni.getStorageSync('locale') || '';
		let address = store.state.address || uni.getStorageSync('address');
		if(locale == 'zh-Hans'){
			locale = 'zh-CN'
		}else if(locale == 'zh-Hant'){
			locale = 'zh-TW'
		}else if(locale == 'en'){
			locale = 'en-US'
		}
		// 请求前：处理header
		let header = {
			'content-type': 'application/json',
			'Authorization': 'Bearer '+token,
			'lang':locale,
			'address':address
		}

		uni.request({
			// url: url,
			url: baseURL + url,
			data: data,
			header: header,
			method: method,
			success: (res) => {
				res.code = res.statusCode;
				if (res.code >=200 && res.code < 300) {
					resolve({
						code:200,
						data:res.data,
					})
				} else if (res.code == 401) {
					// 未登录
					uni.removeStorageSync('token');
					uni.removeStorageSync('address');
					store.commit("setAddress", '')
					uni.navigateTo({
						url: '/pages/index/login',
						animationType: 'pop-in',
						animationDuration: 300
					})
					resolve({
						code:401,
						data:res.data,
					})
					setTimeout(() => {
						uni.showToast({
							title: res.data,
							icon: 'none'
						})
					}, 500)
				} else {
					// 其他错误
					uni.showToast({
						title: res.data,
						icon: 'none'
					})
					resolve({
						code:0,
						data:res.data,
					})
				}
			},
			fail: (err) => {
				uni.showToast({
					title: err.errMsg,
					icon: 'none'
				})
				reject(err)
			},
		});
	})
}

/*GET请求*/
function get(url, data = {}, loading = false) {
	return request(url, data, 'GET', loading).then(data => data).catch(err => err)
}
/*POST请求*/
function post(url, data = {}, loading = false) {
	return request(url, data, 'POST', loading).then(data => data).catch(err => err)
}

/*POST请求*/
function put(url, data = {}, loading = false) {
	return request(url, data, 'PUT', loading).then(data => data).catch(err => err)
}
/*POST请求*/
function del(url, data = {}, loading = false) {
	return request(url, data, 'DELETE', loading).then(data => data).catch(err => err)
}

var http = {
	post,
	get,
	put,
	del
};
export default http;